package com.cmeduSystem.webadmin.upms.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.cmeduSystem.common.core.annotation.MyRequestBody;
import com.cmeduSystem.common.core.constant.ErrorCodeEnum;
import com.cmeduSystem.common.core.object.*;
import com.cmeduSystem.common.core.util.MyCommonUtil;
import com.cmeduSystem.common.core.util.MyModelUtil;
import com.cmeduSystem.common.log.annotation.OperationLog;
import com.cmeduSystem.common.log.model.constant.SysOperationLogType;
import com.cmeduSystem.webadmin.upms.dto.SysConfDto;
import com.cmeduSystem.webadmin.upms.model.SysConf;
import com.cmeduSystem.webadmin.upms.service.SysConfService;
import com.cmeduSystem.webadmin.upms.vo.SysConfVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 系统配置接口。
 *
 * @author xulei
 * @date 2025-09-04
 */
@Tag(name = "系统配置接口")
@Slf4j
@RestController
@RequestMapping("/admin/upms/sysConf")
public class SysConfController {

    @Autowired
    private SysConfService sysConfService;

    /**
     * 更新系统配置数据。
     *
     * @param sysConfDto 更新对象。
     * @return 应答结果对象。
     */
    @SaCheckPermission("sysConf.all")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody SysConfDto sysConfDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(sysConfDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        SysConf sysConf = MyModelUtil.copyTo(sysConfDto, SysConf.class);
        SysConf originalSysConf = sysConfService.getSysConfByCode(sysConfDto.getConfCode());
        if (originalSysConf == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        if (!sysConfService.update(sysConf, originalSysConf)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 查看指定系统配置对象详情。
     *
     * @param confCode 配置编码。
     * @return 应答结果对象，包含对象详情。
     */
    @GetMapping("/view")
    public ResponseResult<SysConfVo> view(@RequestParam String confCode) {
        SysConf sysConf = sysConfService.getSysConfByCode(confCode);
        if (sysConf == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success(sysConf, SysConfVo.class);
    }
}